package task04;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args){
        ObjectInputStream in = null;
        ObjectOutputStream out = null;
        Socket s=null;
        Scanner scanner = new Scanner(System.in);

        System.out.println("==========用户登陆客户端==========");
        System.out.println("请输入用户名：");
        String username = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();
        User user = new User(username, password);
        UserMessage req = new UserMessage(user);

        try {
            String serverHost = "127.0.0.1";
            int serverPort = 8888;
            s = new Socket(serverHost, serverPort);

            // 创建对象输入输出流，与socket连接
            out = new ObjectOutputStream(s.getOutputStream());
            in = new ObjectInputStream((s.getInputStream()));

            // 从socket向server发出登陆信息
            out.writeObject(req);
            // 从socket读取server返回的登陆信息
            UserMessage resp = (UserMessage)in.readObject();// block until response is received

            // 判断登陆结果
            if ("success".equals(resp.getType())) {
                System.out.println("登陆成功");
            }else if ("fail".equals(resp.getType())){
                System.out.println("登陆失败");
            }else System.out.println("连接错误");

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != in) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
